package singleton;


/**
 * @ClassName SingletonDemo
 * @Description 单例模式
 * @Author leejiliang
 * @DateTime 2021/2/23 17:07
 * @Version 1.0
 */
public class SingletonDemo {
	public static void main(String[] args) {
//		final HungrySingleton hungrySingleton  = new HungrySingleton();
		final HungrySingleton instance = HungrySingleton.getInstance();
		instance.exec();

		final LazySingleton lazySingleton = LazySingleton.getInstance();
	}
}

/**
 * 饿汉模式
 */
class HungrySingleton {

	private static  HungrySingleton instance = new HungrySingleton();
	private HungrySingleton() {
	}

	public static HungrySingleton getInstance() {
		return instance;
	}

	public void exec() {
		System.out.println("do something");
	}
}

/**
 * 线程不安全的,懒汉模式
 */
class LazySingleton{
	private static LazySingleton instance;

	private LazySingleton() {

	}

	public static LazySingleton getInstance() {
		if (instance == null) {
			instance = new LazySingleton();
		}
		return instance;
	}
}

/**
 * 双重检索的单例模式
 */
class DoubleCheckSingleton {
	private static DoubleCheckSingleton instance;

	private DoubleCheckSingleton() {

	}

	public static DoubleCheckSingleton getInstance() {
		if (instance == null) {
			synchronized (DoubleCheckSingleton.class) {
				if (instance == null) {
					instance = new DoubleCheckSingleton();
				}
			}
		}
		return instance;
	}
}

/**
 * 基于静态内部类实现的单例模式
 */
class InnerSingleton{

	private InnerSingleton() {

	}

	static class InnerClassSingleton{
		public final static InnerSingleton innerSingleton = new InnerSingleton();
	}

	public static InnerSingleton getInstance() {
		return InnerClassSingleton.innerSingleton;
	}

}